/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.cms;

import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.dao.cms.ChannelCostDao;
import net.dgg.dggcloud.service.jrcrm.entity.cms.ChannelCost;
import net.dgg.dggcloud.service.entity.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName: ChannelCostService
 * @Description:
 * @Author 汤宏
 * @date 2017/11/20 14:58
 */
@Service
public class ChannelCostService extends BaseService {
    @Autowired
    private ChannelCostDao channelCostDao;
    @Autowired
    private KeyWorker keyWorker;
    /**
     * 根据来源渠道编码查询成本方式
     * @param channelCode
     * @return
     */
    public ChannelCost queryByChannelCode(String channelCode) {
        ChannelCost channelCost = null;
        try {
            channelCost = new ChannelCost();
            channelCost.setChannelCode(channelCode);
            channelCost = this.repository.get(channelCost);
        } catch (Exception e) {
            logger.error("查询失败！" + e.getMessage());
            throw new BizException("查询失败！", 10001);
        }
        return channelCost;
    }
    /**
     * 新增更新渠道成本
     *
     * @param channelCost
     * @param loger
     */
    public void saveOrUpdateChannelCost(ChannelCost channelCost,User loger) {
        try {
            //查询渠道 Code是否存在成本设置
            ChannelCost channelCostNow = this.queryByChannelCode(channelCost.getChannelCode());
            //不存在执行新增
            if(null==channelCostNow){
                channelCostNow = new ChannelCost();
                channelCostNow.setId(keyWorker.nextId());
                channelCostNow.setCreateUser(loger);
            }else{
                channelCostNow.setUpdaterUser(loger);
            }
            channelCostNow.setChannelCode(channelCost.getChannelCode());
            channelCostNow.setChannelName(channelCost.getChannelName());
            channelCostNow.setCostType(channelCost.getCostType());
            channelCostNow.setCost(channelCost.getCost());
            channelCostNow.setIsView(channelCost.getIsView());
            channelCostNow.setStatus(channelCost.getStatus());
            channelCostNow.setRemark(channelCost.getRemark());
            this.repository.saveOrUpdate(channelCostNow);
        } catch (Exception e) {
            logger.error("新增更新渠道成本失败！" + e.getLocalizedMessage());
            throw new BizException("新增更新渠道成本失败！"+e.getLocalizedMessage(), 10001);
        }
    }
}
